package net.guruqu.rvoView;

import java.util.LinkedList;
import java.util.Vector;

import com.jme.math.Vector2f;
import com.jme.math.Vector3f;
import com.jme.renderer.ColorRGBA;
import com.jme.renderer.Renderer;
import com.jme.scene.Node;
import com.jme.scene.Point;
import com.jme.scene.Spatial.LightCombineMode;
import com.jme.scene.Spatial.TextureCombineMode;
import com.jme.scene.state.BlendState;
import com.jme.scene.state.LightState;
import com.jme.scene.state.ZBufferState;
import com.jme.system.DisplaySystem;

public class ControlPointGroup {
	LinkedList<Vector2f> controlPoints;
	Vector<Vector2f[]> roadMapEdge;
	Node renderNode;
	ColorRGBA pointColors;
	int cpPointSize;

	public Vector<Vector2f[]> getRoadMapEdge() {
		return roadMapEdge;
	}

	public ControlPointGroup() {
		controlPoints = new LinkedList<Vector2f>();
		roadMapEdge = new Vector<Vector2f[]>();
	}

	public LinkedList<Vector2f> getControlPoints() {
		return controlPoints;
	}

	public Node getRenderNode() {
		if (renderNode == null) {
			renderNode = new Node("Agent Group");
			pointColors = new ColorRGBA(0.4f, 0.2f, 0.8f, 0.8f);
			cpPointSize = 20;

			renderNode.setTextureCombineMode(TextureCombineMode.Off);
			renderNode.setLightCombineMode(LightCombineMode.Off);

			ZBufferState rs = DisplaySystem.getDisplaySystem().getRenderer()
					.createZBufferState();
			rs.setFunction(ZBufferState.TestFunction.Always);
			rs.setWritable(false);
			renderNode.setRenderState(rs);

			BlendState bs = DisplaySystem.getDisplaySystem().getRenderer()
					.createBlendState();
			bs.setEnabled(true);
			bs.setBlendEnabled(true);
			renderNode.setRenderState(bs);

			LightState lightState = DisplaySystem.getDisplaySystem()
					.getRenderer().createLightState();
			lightState.setEnabled(true);
			renderNode.setRenderState(lightState);

			renderNode.setRenderQueueMode(Renderer.QUEUE_SKIP);
			renderNode.updateRenderState();
		}
		return renderNode;
	}

	public Vector2f selectUnit(float x, float y, float scale) {
		for (Vector2f v2f : controlPoints) {
			if ((v2f.x - x) * (v2f.x - x) + (v2f.y - y) * (v2f.y - y) < cpPointSize
					* cpPointSize * scale * scale) {
				return v2f;
			}
		}
		return null;
	}

	public void clear() {
		controlPoints.clear();
		roadMapEdge.clear();
		updateNode();
	}

	public void updateNode() {
		if (renderNode == null)
			return;
		renderNode.detachAllChildren();
		Vector3f v3f[] = new Vector3f[controlPoints.size()];
		ColorRGBA c3f[] = new ColorRGBA[controlPoints.size()];
		int i = 0;
		for (Vector2f ma : controlPoints) {
			v3f[i] = new Vector3f(ma.x, 0, ma.y);
			c3f[i] = pointColors;
			i++;
		}
		Point point = new Point("Control Point Rneder", v3f, null, c3f, null);
		point.setPointSize(cpPointSize);
		renderNode.attachChild(point);
		renderNode.updateModelBound();
	}
}
